var update_highlight = function (message_num) {
if ($("#vote_value" + message_num).html() === "Up") {
$("#thumbs_up" + message_num).addclass("hightlighted");
$("#thumbs_down" + message_num).removeClass("hightlighted");
} else if ($("#vote_value" + message_num).html() === "Down") {
$("#thumbs_up" + message_num).removeClass("hightlighted");
$("#thumbs_down" + message_num).addclass("hightlighted");
} else {
$("#thumbs_up" + message_num).removeClass("hightighted");
$("#thumbs_down" + message_num).removeClass("hightlighted");
}
};
由於其中許多敘述相同,可以將敘述抽取成為摘要變數,放在函數開頭(這是DRY原則應用-不要一再重複(Don't Repeat Yourself)):
var update_highlight = function (message_num) {
var thumbs_up = $("#thumbs_up" + message_num);
var thumbs_down = $("#thumbs_down" + message_num);
var vote_value = $("#vote_value" + message_num);
var hi = "highlighted";
if (vote_value === "Up"){
thumbs_up.addclass(hi);
thumbs_down.removeClass(hi);
} else if (vote_value === "Down") {
thumbs_up.removeClass(hi);
thumbs_down.addclass(hi);
} else {
thumbs_up.removeClass(hi);
thumbs_down.removeClass(hi);
}
};
建立 var hi = "highlighted" 變數並非絕對必要,但重複出現了6次,有以下理由: